/*
 * Copyright (c) 2018. czmc All Rights Reserved.
 * Author: czmc
 * Email: zxc6355533@163.com
 * Encoding: UTF-8
 */

package top.stime21.myneighbours.api;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.orhanobut.logger.Logger;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import orgs.apache.commonss.codec.digests.DigestUtilss;
import retrofit2.Converter;
import top.stime21.myneighbours.utils.RSA;


/**
 * Created by czmc on 2016/9/8.
 */
final class GsonDecoderRequestBodyConverter<T> implements Converter<T,RequestBody> {
    private static final MediaType MEDIA_TYPE = MediaType.parse("");
    private static final Charset UTF_8 = Charset.forName("UTF-8");

    private final Gson gson;
    private final TypeAdapter<T> adapter;

    GsonDecoderRequestBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public RequestBody convert(T value) throws IOException {
        //配合@Body
        //如果需要传递实体对象，则把实体放入Map，进行请求
        Map<String, Object> map = new HashMap<String, Object>();//请求集合
        Map<String, Object> head = new HashMap<String, Object>();//请求头
        if(!(value instanceof Map)){
           return RequestBody.create(MediaType.parse(""),"");
        }
        Map<String, Object> data = (HashMap)value;
        String timestamp = System.currentTimeMillis() + "";
        String json = new Gson().toJson(data);
        Logger.json(json.toString());
        String dataStr = Base64Utils.encodeBase64String(json);//对请求体进行base64编码
        String sign = "";
        StringBuilder sb = new StringBuilder();
        sb.append(timestamp);
        sb.append(dataStr);
        sign = DigestUtilss.md5Hex(sb.toString());
        head.put("sign", sign);
        head.put("timestamp", timestamp + "");//时间戳
        map.put("head", head);
        map.put("data", dataStr);
        String data1 = null;
        try {
            data1 = Base64Utils.encode(RSA.encryptByPublicKey(new Gson().toJson(map).getBytes(), ApiManager.Companion.getSECRET()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String str = "data="+data1;
        return RequestBody.create(MEDIA_TYPE,str);
    }

}
